#!/bin/bash

# 快速测试脚本 - 一键完成所有测试
# 使用方法: ./scripts/quick_test.sh
# 或在项目根目录: ./scripts/quick_test.sh

# 注意: 不使用 set -e，因为某些检查命令允许失败

echo "=== 快速测试脚本 ==="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查函数
check_command() {
    if command -v $1 &> /dev/null; then
        echo -e "${GREEN}✓${NC} $1 可用"
        return 0
    else
        echo -e "${RED}✗${NC} $1 不可用"
        return 1
    fi
}

# Step 0: 环境检查
echo "📋 Step 0: 环境检查"
check_command go || exit 1
check_command curl || exit 1
echo ""

# Step 1: 检查 Edge 服务端
echo "🌐 Step 1: 检查 Edge 服务端"
if curl -s http://127.0.0.1:8001/health | grep -q "ok"; then
    echo -e "${GREEN}✓${NC} Edge 服务端运行正常"
else
    echo -e "${RED}✗${NC} Edge 服务端未响应"
    echo -e "${YELLOW}提示:${NC} 请先启动 Edge 服务端"
    exit 1
fi
echo ""

# Step 2: 检查关键文件
echo "🔧 Step 2: 检查关键文件"
missing_files=0

# 检查 zkp/circuit.go
if [ ! -f "zkp/circuit.go" ]; then
    echo -e "${RED}✗${NC} zkp/circuit.go 不存在"
    echo -e "${YELLOW}提示:${NC} 请执行: git pull origin master"
    missing_files=1
else
    # 检查 circuit 是否修复
    if grep -q "mimcHasher.Write(circuit.Secret)" zkp/circuit.go; then
        echo -e "${GREEN}✓${NC} zkp/circuit.go 存在且已修复"
    else
        echo -e "${YELLOW}⚠${NC}  zkp/circuit.go 存在但可能未修复"
    fi
fi

# 检查测试文件
if [ ! -f "cmd/zkp_test/main.go" ]; then
    echo -e "${RED}✗${NC} cmd/zkp_test/main.go 不存在"
    missing_files=1
else
    echo -e "${GREEN}✓${NC} cmd/zkp_test/main.go 存在"
fi

if [ ! -f "cmd/full_test/main.go" ]; then
    echo -e "${RED}✗${NC} cmd/full_test/main.go 不存在"
    missing_files=1
else
    echo -e "${GREEN}✓${NC} cmd/full_test/main.go 存在"
fi

if [ $missing_files -eq 1 ]; then
    echo ""
    echo -e "${RED}发现缺失文件！${NC}"
    echo -e "${YELLOW}请执行以下命令同步代码:${NC}"
    echo "  cd ~/workspace/test"
    echo "  git pull origin master"
    echo "  chmod +x scripts/*.sh"
    exit 1
fi
echo ""

# Step 3: 检查全局密钥文件
echo "🔑 Step 3: 检查全局密钥文件"
if [ -f "auth_proving.key" ]; then
    key_size=$(stat -f%z "auth_proving.key" 2>/dev/null || stat -c%s "auth_proving.key" 2>/dev/null || echo "unknown")
    echo -e "${GREEN}✓${NC} auth_proving.key 已存在 (大小: ${key_size} bytes)"
    echo -e "${YELLOW}注意:${NC} 此密钥为全局统一密钥，请勿删除或修改"
else
    echo -e "${RED}✗${NC} auth_proving.key 不存在"
    echo ""
    echo -e "${YELLOW}❌ 错误: 客户端不能自动生成密钥！${NC}"
    echo ""
    echo "解决方案:"
    echo "  1. 从开发团队获取统一生成的 auth_proving.key"
    echo "  2. 将文件放置在项目根目录 (~/workspace/test/)"
    echo "  3. 重新运行此脚本"
    echo ""
    echo "参考文档: cat README_ZKP.md"
    exit 1
fi
echo ""

# Step 3.5: 检查设备注册状态
echo "📝 Step 3.5: 检查设备注册状态"

# 读取设备配置
if [ ! -f "device_config.json" ]; then
    echo -e "${RED}✗${NC} device_config.json 不存在"
    echo "请先运行程序生成设备配置"
    exit 1
fi

# 提取 device_id（使用 grep 和 sed）
device_id=$(grep -o '"device_id": *"[^"]*"' device_config.json | sed 's/"device_id": *"\([^"]*\)"/\1/')
if [ -z "$device_id" ]; then
    echo -e "${RED}✗${NC} 无法从 device_config.json 读取 device_id"
    exit 1
fi

echo "   设备 ID: $device_id"

# 检查设备是否已在 Edge 服务器注册
echo "   检查注册状态..."
http_code=$(curl -s -o /tmp/device_check.json -w "%{http_code}" http://127.0.0.1:8001/api/v1/devices/$device_id)

if [ "$http_code" = "200" ]; then
    echo -e "${GREEN}✓${NC} 设备已在 Edge 服务器注册"
else
    echo -e "${YELLOW}⚠${NC}  设备未注册，开始注册..."

    # 提取 secret 和 commitment
    secret=$(grep -o '"secret": *"[^"]*"' device_config.json | sed 's/"secret": *"\([^"]*\)"/\1/')
    commitment=$(grep -o '"commitment": *"[^"]*"' device_config.json | sed 's/"commitment": *"\([^"]*\)"/\1/')

    # 如果 commitment 为空，需要先计算
    if [ -z "$commitment" ] || [ "$commitment" = "null" ] || [ "$commitment" = '""' ]; then
        echo "   计算 commitment..."
        # 使用辅助工具计算 commitment
        commitment=$(go run ./cmd/compute_commitment/main.go "$secret" "$device_id" 2>&1)
        if [ $? -ne 0 ]; then
            echo -e "${RED}✗${NC} 计算 commitment 失败"
            echo "$commitment"
            exit 1
        fi
        echo "   Commitment: $commitment"

        # 更新 device_config.json
        # 使用 Python/Perl/直接写入的方式更新 JSON
        tmp_config=$(mktemp)
        if command -v jq &> /dev/null; then
            # 如果有 jq，使用 jq 更新
            jq ".commitment = \"$commitment\"" device_config.json > "$tmp_config"
            mv "$tmp_config" device_config.json
        else
            # 否则使用 sed
            sed "s/\"commitment\": *\"[^\"]*\"/\"commitment\": \"$commitment\"/" device_config.json > "$tmp_config"
            mv "$tmp_config" device_config.json
        fi
    fi

    # 注册设备到 Edge 服务器
    # 从 device_id 推断 sensor_type（TH_SENSOR -> temperature）
    if [[ "$device_id" == *"TH_"* ]] || [[ "$device_id" == *"TEMP"* ]]; then
        sensor_type="temperature"
    elif [[ "$device_id" == *"CO2"* ]]; then
        sensor_type="co2"
    elif [[ "$device_id" == *"CO_"* ]]; then
        sensor_type="co"
    else
        sensor_type="temperature"  # 默认
    fi

    register_payload=$(cat <<EOF
{
  "device_id": "$device_id",
  "device_type": "sensor",
  "sensor_type": "$sensor_type",
  "cabinet_id": "CABINET_A1",
  "public_key": "0000000000000000000000000000000000000000000000000000000000000000",
  "commitment": "$commitment",
  "model": "Generic Sensor",
  "manufacturer": "EdgeTech",
  "firmware_ver": "1.0.0"
}
EOF
)

    register_response=$(curl -s -w "\n%{http_code}" -X POST http://127.0.0.1:8001/api/v1/devices \
        -H "Content-Type: application/json" \
        -d "$register_payload")

    register_http_code=$(echo "$register_response" | tail -n 1)

    if [ "$register_http_code" = "201" ]; then
        echo -e "${GREEN}✓${NC} 设备注册成功"
        # 更新 device_config.json 的 registered 字段
        tmp_config=$(mktemp)
        if command -v jq &> /dev/null; then
            jq '.registered = true' device_config.json > "$tmp_config"
            mv "$tmp_config" device_config.json
        else
            sed 's/"registered": *false/"registered": true/' device_config.json > "$tmp_config"
            mv "$tmp_config" device_config.json
        fi
    else
        echo -e "${RED}✗${NC} 设备注册失败 (HTTP $register_http_code)"
        echo "响应: $(echo "$register_response" | head -n -1)"
        exit 1
    fi
fi
echo ""

# Step 4: 测试 ZKP 基础功能
echo "🔐 Step 4: 测试 ZKP 基础功能"
echo "   运行 zkp_test..."
if [ ! -f "cmd/zkp_test/main.go" ]; then
    echo -e "${RED}✗${NC} cmd/zkp_test/main.go 不存在，跳过测试"
else
    # 确保在项目根目录运行，这样可以找到 auth_proving.key
    # 使用 -C 选项不会改变工作目录
    if timeout 300 go run ./cmd/zkp_test/main.go > /tmp/zkp_test.log 2>&1; then
        echo -e "${GREEN}✓${NC} ZKP 测试通过"
        grep "✅" /tmp/zkp_test.log | head -5 || true
    else
        echo -e "${RED}✗${NC} ZKP 测试失败"
        echo -e "${YELLOW}错误日志 (最后 30 行):${NC}"
        tail -30 /tmp/zkp_test.log
        echo ""
        echo -e "${YELLOW}查看完整日志: cat /tmp/zkp_test.log${NC}"
        exit 1
    fi
fi
echo ""

# Step 5: 识别传感器
echo "📡 Step 5: 传感器识别"
echo -e "${YELLOW}是否需要识别串口传感器? (y/n) [默认: n]${NC}"
read -t 5 -n 1 response || response="n"
echo ""

if [ "$response" = "y" ]; then
    echo "请选择串口:"
    echo "  1) /dev/ttyCH9344USB0"
    echo "  2) /dev/ttyCH9344USB1"
    echo "  3) 跳过"
    read -p "> " port_choice

    case $port_choice in
        1) ./scripts/identify_sensor.sh /dev/ttyCH9344USB0 ;;
        2) ./scripts/identify_sensor.sh /dev/ttyCH9344USB1 ;;
        *) echo "跳过传感器识别" ;;
    esac
    echo ""
else
    echo "跳过传感器识别"
    echo ""
fi

# Step 6: 运行完整测试
echo "🚀 Step 6: 运行完整 ZKP 认证流程测试"
if [ ! -f "cmd/full_test/main.go" ]; then
    echo -e "${YELLOW}⚠${NC}  cmd/full_test/main.go 不存在，跳过测试"
else
    echo -e "${YELLOW}准备测试 2 个传感器:${NC}"
    echo "  - TH_SENSOR (温湿度)"
    echo "  - CO2_SENSOR (CO2)"
    echo ""
    echo "开始测试? (y/n) [默认: y]"
    read -t 5 -n 1 response || response="y"
    echo ""

    if [ "$response" = "y" ] || [ "$response" = "" ]; then
        echo "执行完整测试..."
        # 确保在项目根目录运行
        if timeout 600 go run ./cmd/full_test/main.go | tee /tmp/full_test.log; then
        echo ""
        echo -e "${GREEN}✓${NC} 完整测试通过"

            # 统计结果
            success_count=$(grep -c "✅ 认证成功" /tmp/full_test.log || echo "0")
            echo ""
            echo "📊 测试结果统计:"
            echo "   - 认证成功: $success_count 个设备"

            if [ -f "devices_config.json" ]; then
                if command -v jq &> /dev/null; then
                    device_count=$(jq '. | length' devices_config.json 2>/dev/null || echo "N/A")
                    echo "   - 配置已保存: $device_count 个设备"
                else
                    echo "   - 配置已保存: devices_config.json"
                fi
            fi
        else
            echo -e "${RED}✗${NC} 测试失败"
            echo -e "${YELLOW}请查看日志: /tmp/full_test.log${NC}"
            exit 1
        fi
    else
        echo "跳过完整测试"
    fi
fi

echo ""
echo "============================================================"
echo -e "${GREEN}✅ 所有测试完成!${NC}"
echo "============================================================"
echo ""
echo "📝 生成的文件:"
[ -f "auth_proving.key" ] && echo "   - auth_proving.key (ZKP proving key)"
[ -f "auth_verifying.key" ] && echo "   - auth_verifying.key (ZKP verifying key)"
[ -f "devices_config.json" ] && echo "   - devices_config.json (设备配置)"
echo ""
echo "📚 查看文档:"
echo "   - cat SENSOR_TEST_GUIDE.md"
echo "   - cat README_ZKP.md"
echo ""
echo "🔍 查看日志:"
echo "   - cat /tmp/zkp_test.log"
echo "   - cat /tmp/full_test.log"
echo ""
